package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkd.entity.Partner;
import com.lkd.entity.VendingMachine;
import com.lkd.mapper.PartnerMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.service.PartnerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.vo.PageBean;
import com.lkd.vo.PartnerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 合作商表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-20
 */
@Service
public class PartnerServiceImpl extends ServiceImpl<PartnerMapper, Partner> implements PartnerService {

    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    //分页查询
    @Override
    public PageBean<PartnerVo> search(String name, Integer pageIndex, Integer pageSize) {
        Page<Partner>page=new Page<>(pageIndex,pageSize);

        LambdaQueryWrapper<Partner> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(name),Partner::getName,name);
        page = getBaseMapper().selectPage(page,wrapper);


        List<PartnerVo>partnerVoList=page.getRecords().stream().map(partner -> {
            PartnerVo partnerVo =BeanUtil.copyProperties(partner,PartnerVo.class);

            LambdaQueryWrapper<VendingMachine> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(VendingMachine::getOwnerId,partnerVo.getId());
            List<VendingMachine> vendingMachineList = vendingMachineMapper.selectList(wrapper1);
            partnerVo.setVmCount(vendingMachineList.size());
            return partnerVo;
        }).collect(Collectors.toList());
        return new PageBean<>(page,partnerVoList);
    }

    //获取合作商详情
    @Override
    public PartnerVo findById(Integer id) {
        Partner partner = getBaseMapper().selectById(id);
        PartnerVo partnerVo = BeanUtil.copyProperties(partner, PartnerVo.class);

        List<VendingMachine> vendingMachineList = vendingMachineMapper.selectList(new LambdaQueryWrapper<VendingMachine>().eq(VendingMachine::getOwnerId, id));
        partnerVo.setVmCount(vendingMachineList.size());

        return partnerVo;
    }
}
